﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Resources;

using Epic.Core;

namespace Epic.ComponentServices
{
    [AttributeUsage(AttributeTargets.All)]
    public class LocalizedDescriptionAttribute : DescriptionAttribute
    {
#pragma warning disable 1591

        public ResourceManager ResourceManager { get; set; }
        public CultureInfo Culture { get; set; }

        public string DescriptionKey { get; set; }

        public string FallbackDescription { get; set; }

        #region Constructors

        public LocalizedDescriptionAttribute() { }
        public LocalizedDescriptionAttribute(string key)
        {
            DescriptionKey = key;
        }
        public LocalizedDescriptionAttribute(ResourceManager resourceManager, string key = null)
            : this(key)
        {
            if (resourceManager == null)
                throw NewException.ArgumentNull(() => resourceManager);

            this.ResourceManager = resourceManager;
        }

        #endregion

        protected virtual string GetResourceKey(string propertyKey)
        {
            return "Property" + propertyKey + "Description";
        }

        public override string Description
        {
            get
            {
                string candidate = null;
                if (ResourceManager != null)
                    candidate = ResourceManager.GetString(GetResourceKey(DescriptionKey), Culture);

                return candidate ?? FallbackDescription ?? "";
            }
        }
    }

    public class PrefixedLocalizedDescriptionAttribute : LocalizedDescriptionAttribute
    {
        public string Prefix { get; set; }

        public PrefixedLocalizedDescriptionAttribute() { }
        public PrefixedLocalizedDescriptionAttribute(string prefix)
        {
            this.Prefix = prefix;
        }
        public PrefixedLocalizedDescriptionAttribute(ResourceManager resourceManager, Type componentType, string key = null)
            : this(resourceManager, componentType.Name, key)
        { }
        public PrefixedLocalizedDescriptionAttribute(ResourceManager resourceManager, string prefix, string key = null)
            : base(resourceManager, key)
        {
            this.Prefix = prefix;
        }

        protected override string GetResourceKey(string propertyKey)
        {
            return base.GetResourceKey(Prefix + propertyKey);
        }
    }
}
